from fastapi import APIRouter, Depends, Request
from schemas.common import RETURN
from sqlalchemy.future import select
from sqlmodel.ext.asyncio.session import AsyncSession
from database.mysql import get_async_session
import models.admin.system.Config as ConfigModel
from database.redis import update_config_to_redis
from server.Base import BaseServer
import models.admin.system.Admin as AdminModel
from core.Depend import has_permission

router = APIRouter(prefix="/config", tags=["系统配置"])

# 增加配置
@router.post("/add", response_model=RETURN)
async def add_config(config: ConfigModel.Config,req: Request, session: AsyncSession = Depends(get_async_session),adminuser:AdminModel.redis_admin = Depends(has_permission("system_admin_config_add"))):
    # code 不能重复
    state= select(ConfigModel.Config).where(ConfigModel.Config.code == config.code)
    result = await session.exec(state)
    isHas:ConfigModel.Config = result.scalars().first()
    if isHas:
        return RETURN.fail("配置标识已存在")
    await BaseServer(ConfigModel.Config).create(config.model_dump())
    await update_config_to_redis(req.app)
    return RETURN.success("添加成功")

# 删除配置
@router.delete("/delete", response_model=RETURN)
async def delete_config(id: int,req: Request, session: AsyncSession = Depends(get_async_session),adminuser:AdminModel.redis_admin = Depends(has_permission("system_admin_config_delete"))):
    # 查询是否有子配置
    state = select(ConfigModel.Config).where(ConfigModel.Config.id == id)
    result = await session.exec(state)
    isHas:ConfigModel.Config = result.scalars().first()
    if isHas.code == "base" or isHas.code == "email":
        return RETURN.fail("基础配置不可删除")
    # parent_code为base or email的配置不可删除
    if isHas.parent_code == "base" or isHas.parent_code == "email":
        return RETURN.fail("基础配置不可删除")

    if isHas:
      child_state = select(ConfigModel.Config).where(ConfigModel.Config.parent_code == isHas.code)
      child_result = await session.exec(child_state)
      #查询出所有字配置，一起删除掉
      children = child_result.scalars().all()
      ids = [child.id for child in children]
      await BaseServer(ConfigModel.Config).batch_delete(ids)
    else:
        return RETURN.fail("配置不存在")  
    config = await BaseServer(ConfigModel.Config).get(id)
    if not config:
        return RETURN.fail("配置不存在")
    # redis 删除 如果parent_code为空，则直接删除
    if not config["parent_code"]:
      key = config["code"]
    else:
      key = f"{config['parent_code']}:{config['code']}"
    await req.app.state.cache.delete(key)
    await BaseServer(ConfigModel.Config).delete(id)
    return RETURN.success("删除成功")

# 修改配置
@router.put("/update", response_model=RETURN)
async def update_config(config: ConfigModel.editConfig,req: Request,adminuser:AdminModel.redis_admin = Depends(has_permission("system_admin_config_update"))):
    await BaseServer(ConfigModel.Config).update(config.model_dump())
    await update_config_to_redis(req.app)
    return RETURN.success("修改成功")

# 批量更新配置
@router.put("/batch_update", response_model=RETURN)
async def update_config_batch(configs: list[ConfigModel.editBathListConfig],req: Request,adminuser:AdminModel.redis_admin = Depends(has_permission("system_admin_config_batch_update"))):
    for config in configs:
        await BaseServer(ConfigModel.Config).update(config.model_dump())
    await update_config_to_redis(req.app)
    return RETURN.success("修改成功")

# 查询配置 
@router.post("/list", response_model=RETURN)
async def list_config(parent_code: str|None = None,  session: AsyncSession = Depends(get_async_session),adminuser:AdminModel.redis_admin = Depends(has_permission("system_admin_config_list"))):
    state = select(ConfigModel.Config).where(ConfigModel.Config.parent_code == parent_code).order_by(ConfigModel.Config.weigh)
    result = await session.exec(state)
    data = result.scalars().all()
    return RETURN.success("查询成功", data)